//
//  LATileOverlay(MK).m
//  2bulu-NewAssistant
//
//  Created by Kent Peifeng Ke on 2/28/15.
//  Copyright (c) 2015 È≠èÊñ∞Êù∞. All rights reserved.
//

#import "LAGTileOverlay.h"

static NSURLSession *gMapLoadSession;

typedef void (^LATileOverlayResultCallback)(NSData *, NSError *);

@interface LAGTileOverlay()

@property (nonatomic, strong,readonly) NSURLSession *mapLoadSession;


@end

@implementation LAGTileOverlay
{

    __weak MKTileOverlayRenderer * _renderer;
    NSString *_localUrlTemplate;
    
}



+(void)clearTileCache
{
    NSURLCache *cache = gMapLoadSession.configuration.URLCache;
    [cache removeAllCachedResponses];
}

+(NSUInteger)cachedDiskCapacity
{
    NSURLCache *cache = gMapLoadSession.configuration.URLCache;
    return cache.currentDiskUsage;
}

+(nullable NSURL *)urlForTilePath:(MKTileOverlayPath)path withTemplate:(NSString *)urlTemplate
{
    if(!urlTemplate)
        return nil;
    
    NSString *columnStr = [NSString stringWithFormat:@"%ld",(long)path.x];
    NSString *rowStr = [NSString stringWithFormat:@"%ld",(long)path.y];
    NSString *levelStr = [NSString stringWithFormat:@"%ld",(long)path.z];
    
    NSString *urlString = [urlTemplate stringByReplacingOccurrencesOfString:@"{x}" withString:columnStr];
    urlString = [urlString stringByReplacingOccurrencesOfString:@"{y}" withString:rowStr];
    urlString = [urlString stringByReplacingOccurrencesOfString:@"{z}" withString:levelStr];
    
    return [NSURL URLWithString:urlString];
}

-(nullable NSString *)alternateUrlTemplate
{
    NSString *alternatePara;
    
    NSString *urlTemplate = nil;
    if(alternatePara)
        urlTemplate = [self.URLTemplate stringByReplacingOccurrencesOfString:@"{s}" withString:alternatePara];
    
    return urlTemplate;
}

#pragma mark-

- (instancetype)initWithRemoteURLTemplate:(nullable NSString *)remoteURLTemplate
                         localUrlTemplate:(nullable NSString*)localUrlTemplate
{
    self = [super initWithURLTemplate:remoteURLTemplate];
    if(self)
    {
        _localUrlTemplate = localUrlTemplate;
    }
    return self;
}




-(MKTileOverlayRenderer *)renderer
{
    MKTileOverlayRenderer *r = _renderer;
    if(!r)
    {
        r = [[MKTileOverlayRenderer alloc] initWithTileOverlay:self];
        _renderer = r;
    }
    
    return r;
}

-(void)setTileSize:(CGSize)tileSize
{
    CGSize preSize = self.tileSize;
    [super setTileSize:tileSize];
    if(_renderer)
    {
        if(preSize.width != tileSize.width || preSize.height != tileSize.height)
        {
            [_renderer reloadData];
        }
    }
    
}

//llf  2016.10.18
- (NSURLSession *)mapLoadSession
{
    if (gMapLoadSession == nil)
    {
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
       // sessionConfig.timeoutIntervalForRequest = 120.0;
        
        //cache
        NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024*20 diskCapacity:1024*1024*500 diskPath:@"LAMapTiles"];
        sessionConfig.URLCache = cache;
        sessionConfig.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;//NSURLRequestReturnCacheDataElseLoad;//NSURLRequestUseProtocolCachePolicy;//NSURLRequestReturnCacheDataElseLoad;

        gMapLoadSession = [NSURLSession sessionWithConfiguration:sessionConfig];
    }
    return gMapLoadSession;
}



//本地瓦片存储路径


//////llf added 2016.10.18
- (NSURL *)URLForTilePath:(MKTileOverlayPath)path
{
    NSURL *url = [[self class] urlForTilePath:path withTemplate:_localUrlTemplate];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:url.path])
    {
        //do nothing
    }
    else if (!self.onlyLoadLocalResource)//可以在线加载
    {
        url = [super URLForTilePath:path];
    }
    
    return url;
    
}


-(void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *, NSError *))result
{
    
    __weak typeof(self) wSelf = self;
    //llf modified 启用缓存功能
    NSURLSessionDataTask *loadSessionTask = [self.mapLoadSession dataTaskWithURL:[self URLForTilePath:path]
                                                               completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                                             {
                                                 if(result)
                                                 {
                                                     NSData *processedData = data;
                                                     
                                                     #warning todo 这里要可以适配自定义的tileSize
//                                                      UIImage *image = [UIImage imageWithData:data];
//                
//
//                                                     if(image.size.width != wSelf.tileSize.width)
//                                                     {
//                                                         image = [image resizedImageToSize:wSelf.tileSize];
//                                                         processedData = UIImageJPEGRepresentation(image,0.72);
//                                                     }
//                                                     else if([[UIDevice currentDevice].systemVersion hasPrefix:@"8"])//ios8系统无条件做data转换
//                                                     {
//                                                         processedData = UIImageJPEGRepresentation(image,0.72);
//                                                     }

                                                     result(processedData, error);
                                                 }
                                                 
                                             }];
    
        [loadSessionTask resume];
}




@end

